# -*- coding: utf-8 -*-
class ClaimReturnedController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:newReturnedFromClaim,:editReturnedFromClaim]
  
  def claimReturnedList
    
  end

  def newReturnedFromClaim
    claim = Claim.find(params[:id],:include=>[:logistics])
    @logisticsName = claim.logistics.name
  end

  def getAllClaimReturneds
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      paramsHash[:offset] = params[:start].to_i
      paramsHash[:limit] = params[:limit].to_i

      conditionsStr = ''

      if params[:order_number].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'seq_number in (:order_number)'
        else
          conditionsStr = conditionsStr+' AND seq_number in (:order_number)'
        end
        conditionsHash[:order_number] = params[:order_number].split(/,/)
      end

      if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status like :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
        end
        conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
      elsif params[:auditing_status] == ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status = :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status = :auditing_status'
        end
        conditionsHash[:auditing_status] = ''
      end

      if params[:customer_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'customer_id = :customer_id'
        else
          conditionsStr = conditionsStr+' AND customer_id = :customer_id'
        end
        conditionsHash[:customer_id] = params[:customer_id].to_i
      end

      #销售员
      if params[:sales_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'sales_id = :sales_id'
        else
          conditionsStr = conditionsStr+' AND sales_id = :sales_id'
        end
        conditionsHash[:sales_id] = params[:sales_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      #显示产品
      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'sale_order_details.product_id = :product_id'
        else
          conditionsStr = conditionsStr+' AND sale_order_details.product_id = :product_id'
        end
        conditionsHash[:product_id] = params[:product_id].to_i
      end

      #显示产品
      if params[:department_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'department_id = :department_id'
        else
          conditionsStr = conditionsStr+' AND department_id = :department_id'
        end
        conditionsHash[:department_id] = params[:department_id].to_i
      end

      count = ClaimReturned.countAllClaimReturneds conditionsStr,conditionsHash
      claimReturneds = ClaimReturned.findAllClaimReturneds conditionsStr,conditionsHash,paramsHash

      jsonStr="{totalProperty:"+count.to_s+",root:"+claimReturneds.to_json(:include=>[:logistics,:purchase_order,:warehousing_entry,:department,:employee,:warehouse,:claim])+"}"
      logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  def getClaimReturnedById
    claimReturned = ClaimReturned.find(params[:id])
    rootStr = claimReturned.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到某索赔的详细信息
  def getClaimReturnedDetailsById

  end


  #此方法作了调整，不用进行整单的转换，用户可对索赔单进行调整，然后再保存，即一个索赔单可对应多个返库单
  def transformClaimIntoReturned
    paramsHash = Util.paramsPreprocesseToHash(params[:data])
    claimId = paramsHash['claim_id']
    warehouseId = paramsHash['warehouse_id']

    claim =  Claim.find(claimId)
    if claim.deal_with_status == Constants::CANCELED
      info = "已经撤消的索赔订单，不可以再转换为返库订单！"
    elsif   claim.store_status == Constants::FINISH_ENTRY
      info = "已经返库完毕的索赔订单，不可以再转换为索赔返库订单！"
    else
      claimReturned = ClaimReturned.new
      claimReturned.claim_id = claim.id
      claimReturned.company_id = claim.company_id
      claimReturned.department_id = claim.department_id
      claimReturned.employee_id = claim.employee_id
      claimReturned.action_date = paramsHash['action_date']
      claimReturned.logistics_id = claim.logistics_id
      claimReturned.amount = claim.amount
      claimReturned.warehouse_id = warehouseId
      claimReturned.warehousing_entry_id = claim.warehousing_entry_id
      claimReturned.purchase_order_id = claim.purchase_order_id
      claimReturned.auditing_status = Constants::PASS_APPLY_ADD
      claimReturned.save!  #先行保存一下，以便生成ID
      claim.store_status = "返库中"
      #为了在进行结算表操作时提前获取ID，这时要提前存储purchaseOrder


      #向详细表中插入products信息
      productsHashArray = paramsHash["products"]
      productsHashArray.each do |productHash|
        #如果不为空则加入
        if productHash["product_id"] !=""
          #得到采购订单的详细价格，只有取出它的详细记录来。
          claimDetail = ClaimDetail.find(productHash["id"])
          claimReturnedDetail = ClaimReturnedDetail.new
          claimReturnedDetail.product_id = productHash["product_id"]
          claimReturnedDetail.quantity = productHash["quantity"]
          claimReturnedDetail.unit_price = claimDetail.unit_price
          claimReturnedDetail.amount = claimReturnedDetail.quantity * claimReturnedDetail.unit_price
          claimReturned.amount = claimReturned.amount + claimReturnedDetail.amount #计算订单总金额
          claimReturnedDetail.description = productHash["description"]
          claimReturnedDetail.claim_id = claimDetail.claim_id
          claimReturned.claim_returned_details << claimReturnedDetail

          #同时生成结算表的内容。
          productCollection = ProductCollection.new
          #copy内容到结算表
          #在进行成功转换后，要同时操作结算表，把此次操作的详细内容，完全拆解开，复制到结算表中。
          productCollection.company_id = claimReturned.company_id
          productCollection.department_id = claimReturned.department_id
          productCollection.employee_id = claimReturned.employee_id
          productCollection.logistics_id = claimReturned.logistics_id
          productCollection.amount = claimReturned.amount
          productCollection.warehouse_id = warehouseId
          productCollection.product_id = claimReturnedDetail.product_id
          productCollection.quantity = productHash["quantity"] #purchaseOrderDetail.quantity
          productCollection.unit_price = claimReturnedDetail.unit_price
          productCollection.unit_amount = claimReturnedDetail.amount
          productCollection.resource_id =  claimReturned.id
          productCollection.resource_type =  ClaimReturned.name
          productCollection.description =  claimReturnedDetail.description
          productCollection.action_date = claimReturned.action_date
          productCollection.claim_id =  claimReturnedDetail.claim_id
          productCollection.save!
        end
      end

      #在这儿再检查，对比一下销售订单与出库单的数量差，以确认要不要添加上“出库完毕”状态
      claimDetails = ClaimDetail.find(:all,:select=>"cd.id,p.id as product_id,p.name as product_name,p.is_suit,p.unit_price,p.number,p.spec,p.unit,cd.quantity,cd.description,newrd.quantity as rd_quantity,(sum(cd.quantity) - ifnull(newrd.quantity,0)) as balance_quantity",:joins =>"cd
left join (select product_id,sum(quantity) as quantity from claim_returned_details crd left join claim_returneds cr on crd.claim_returned_id = cr.id
where cr.claim_id = "+claimId+" AND cr.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id) newrd on newrd.product_id = cd.product_id
left join products p on p.id = cd.product_id
where cd.claim_id =  "+claimId+ " group by cd.product_id having sum(cd.quantity) - ifnull(newrd.quantity,0) > 0")

      if claimDetails.length == 0
        claim.store_status = Constants::FINISH_ENTRY
      end
      
      #开始事务，确保在流水号正常的情况下，保存入库单时,一但出现问题，则循环执行
      begin
        Sequence.transaction do
          #开始为出库单取得流水号
          sequence = Sequence.find(:first,:conditions=>["company_id = ? AND sub_type = ?",session[:company_id],ClaimReturned.name])

          sequence.seq_no = sequence.seq_no + 1
          claimReturned.seq_number = sequence.seq_no
          claimReturned.order_number = sequence.ab + ":" + claimReturned.seq_number.to_s + ":" + Date.today.to_s
          sequence.save!
          claimReturned.save!
          #最后保存采购订单的状态更改。
          claim.save!
        end
      rescue ActiveRecord::StaleObjectError
        #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
        #这里特别指序号产生表。
        logger.info "somebody useing sn before yours.............................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
        retry
      rescue ActiveRecord::RecordNotFound
        logger.info "RecordNotFound................................................................................"
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
      rescue Exception => e
        logger.info "logging......................................................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
        logger.info e
      end
      info = "成功"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到返库订单的详细信息
  def getDetailsById
    claimReturnedDetails =  ClaimReturnedDetail.find_all_by_claim_returned_id(params[:id])
    jsonStr="{totalProperty:"+claimReturnedDetails.length.to_s+",root:"+claimReturnedDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec]}})+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #在编辑时得到可以编辑的详细的索赔信息
  def getDetailsBalanceByIdForEdit
    claimReturnedId = params[:claim_returned_id]
    claimReturned = ClaimReturned.find(claimReturnedId)
    #销售详细
    #balance_quantity为当前最大的可入数量。即修改后的数字不能大于balance_quantity
    claimReturnedDetails = ClaimReturnedDetail.find(:all,:select=>"rd.id,p.id as product_id,p.name as product_name,p.is_suit,p.unit_price,p.number,p.spec,p.unit,rd.quantity,rd.description,newrd.quantity as rd_quantity,(cd.quantity - ifnull(newrd.quantity,0) + rd.quantity) as balance_quantity",:joins =>"rd
left join (select product_id,sum(quantity) as quantity
from claim_returned_details rd left join claim_returneds r on rd.claim_returned_id = r.id
where r.id = #{claimReturned.id} AND r.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by rd.product_id) newrd on newrd.product_id = rd.product_id
left join products p on p.id = rd.product_id
left join claim_returneds cr on cr.id = rd.claim_returned_id
left join claim_details cd on cd.claim_id = cr.claim_id and cd.product_id = rd.product_id
where rd.claim_returned_id =  #{claimReturned.id}")

    jsonStr="{totalProperty:"+claimReturnedDetails.length.to_s+",root:"+claimReturnedDetails.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  def update
    paramsHash = Util.paramsPreprocesseToHash(params[:data])
    #productHash = paramsHash["products"][0]
    claimReturned = ClaimReturned.find(:first,:conditions=>["id = ? AND company_id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status not like ?)",paramsHash['id'],session[:company_id],'%撤消%'])
    if claimReturned != nil
      claimReturned.company_id = session[:company_id]
      claimReturned.department_id = session[:department_id]
      claimReturned.employee_id = session[:employee_id]
      claimReturned.warehouse_id = paramsHash['warehouse_id']
      claimReturned.action_date = paramsHash['action_date']
      claimReturned.description = paramsHash['description']

      claimReturned.audit_opinion = ''
      claimReturned.auditor_id = session[:employee_id]

      claimReturned.auditing_status = Constants::PASS_APPLY_EDIT

      #products信息
      productsHashArray = paramsHash["products"]
      #在这里，要作一个增，删，编辑操作，以前台数据为准。
      #首先各取出前台与后台的ID数组
      fgIdArray = Array.new
      productsHashArray.each do |productHash|
        fgIdArray << productHash["id"].to_i
      end

      bgIdArray = Array.new
      claimReturnedDetails = claimReturned.claim_returned_details
      claimReturnedDetails.each do |claimReturnedDetail|
        bgIdArray << claimReturnedDetail.id
      end

      idIntersectionArray = fgIdArray & bgIdArray
      addIdArray = fgIdArray - idIntersectionArray
      delIdArray = bgIdArray - idIntersectionArray
      #得到要删除的产品Id数组

      if !delIdArray.empty?
        claimReturnedDetails = ClaimReturnedDetail.find(:all,:conditions=>["id in (?)",delIdArray])
        productIdArray = Array.new
        claimReturnedDetails.each do |claimReturnedDetail|
          productIdArray << claimReturnedDetail.product_id
        end
        ClaimReturnedDetail.delete(delIdArray)
        #删除汇总表中的相关内容,要删除记录的要领是结合claimid,productId
        ProductCollection.delete_all(["resource_type = 'ClaimReturned' AND resource_id = ? AND product_id in (?)",claimReturned.id,productIdArray])
      end

      #在进行从新整理数据之前，先把销售订单的总金额置“0”
      claimReturned.amount = 0

      productsHashArray.each do |productHash|
        #只有当用户选择的产品不为空时，才有详细订单。
        if productHash["product_id"] !=""
          #没Id说明是新增加的。
          if productHash["id"] != ""
            claimReturnedDetail = ClaimReturnedDetail.find(productHash["id"].to_i)
            claimReturnedDetail.quantity = productHash["quantity"] #对于出入库来说其实只有数量为唯一的考量。
            claimReturnedDetail.description = productHash["description"]
            claimReturnedDetail.save
            #同时把汇总表中的相关记录进行修改
            ProductCollection.update_all("warehouse_id = #{claimReturned.warehouse_id},quantity = #{claimReturnedDetail.quantity}","resource_type = 'ClaimReturned' AND resource_id = #{claimReturned.id} AND claim_id = #{claimReturnedDetail.claim_id} AND product_id = #{claimReturnedDetail.product_id} AND is_locked = 0")
          end
        end
      end
      claimReturned.save
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
  #申请撤消
  def applyToCancel
    begin
      claim = Claim.find(params[:id])
      sysParam =  SysParam.find_by_company_id(session[:company_id])
      if sysParam.audit_for_claim_cancel == "否"
        claim.auditing_status = Constants::PASS_APPLY_CANCEL
        claim.deal_with_status = Constants::CANCELED
        ProductCollection.delete_all("resource_type = 'Claim' AND resource_id = #{params[:id]}")
        #如果不需要审核，则把汇总表中的数据设置为is_locked = 1
      else
        claim.auditing_status = Constants::AUDIT_APPLY_CANCEL
      end
      claim.auditor_id = session[:employee_id]
      claim.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
end
